<?php

namespace app\api\model\hotel;

use app\api\model\UserCoupon;
use app\common\model\hotel\Hotel as HotelModel;
use app\common\model\hotel\Order as OrderModel;
use app\common\model\User;
use think\Db;
use think\Model;
use traits\model\SoftDelete;


class HotelThirdOrder extends Model
{

    // 订单创建
    const ORDER_CREATE = 0;

    // 订单待入住
    const ORDER_WAIT_CHECKIN = 1;

    //已完成
    const ORDER_COMPLETE = 10;

    //已取消
    const ORDER_CLOSE = -1;
    
    //售后
    const ORDER_REFUND = 4;
    
    public $order_status = [
        self::ORDER_CREATE           => [
            'status'          => self::ORDER_CREATE,
            'name'            => '待支付',
        ],
        self::ORDER_WAIT_CHECKIN           => [
            'status'          => self::ORDER_WAIT_CHECKIN,
            'name'            => '待入住',
        ],
        self::ORDER_COMPLETE           => [
            'status'          => self::ORDER_COMPLETE,
            'name'            => '已完成',
        ],
        self::ORDER_CLOSE           => [
            'status'          => self::ORDER_CLOSE,
            'name'            => '已取消',
        ],
    ];


    use SoftDelete;



    // 表名
    protected $name = 'hotel_third_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];

    //用户订单列表
    public function getUserOrderList($data)
    {
        $order_status = $data['order_status'];

        $where = ['ho.user_id'=>$data['user_id']];

        switch ( $order_status ) {
            case "waitpay"://待支付
                $where['ho.pay_status'] = 0;
                $where['ho.order_status'] = 0;
                break;
            case "waitcheckin"://待入住
                $where['ho.pay_status'] = 1;
                $where['ho.order_status'] = 1;
                break;
            case "complete"://已完成
                $where['ho.order_status'] = 10;
                break;
            case "refund"://售后
                $where['ho.order_status'] = 4;
                break;
        }

        $list = HotelThirdOrder::alias('ho')
            ->where($where)
            ->order('ho.createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        $auto_close = \app\common\model\Config::get(['name'=>'close_time'])->value*60;

        $hotel = new HotelModel();

        foreach ($list as $k=>$v){
            $list[$k]['auto_close'] = $v['createtime'] + $auto_close-time();

            $list[$k]['room_type_info'] = $hotel->room_type_detail($v['hotel_id'],$v['room_type_code']);
            $list[$k]['hotel_info'] = $hotel->get_hotel_detail($v['hotel_id']);
        }

        return $list;
    }

    //用户订单详情
    public function getUserOrderInfo($order_id,$user_id)
    {
        $info = HotelThirdOrder::where(['order_id'=>$order_id])->find();
        //if (!$info)throw new \Exception('不是当前用户订单');

        $auto_close = \app\common\model\Config::get(['name'=>'close_time'])->value*60;

        $info['auto_close'] = $info['createtime'] + $auto_close-time();
        $hotel = new HotelModel();
        //$info['room_type_info'] = $hotel->room_type_detail($info['hotel_id'],$info['room_type_code']);
        //$info['hotel_info'] = $hotel->get_hotel_detail($info['hotel_id']);

        $refund = HotelOrderRefund::get(['order_id'=>$order_id]);
        $info['refund_info'] = $refund;
        return $info;
    }

    //订单取消
    public function orderCancel($order_id)
    {
        Db::startTrans();
        try {
            $info = HotelThirdOrder::where(['order_id'=>$order_id])->find();

            if ($info['order_status']==self::ORDER_CLOSE) {
                throw new \Exception('已取消');
            }

            $data = [
                'order_status'=>self::ORDER_CLOSE,
                'order_status_name'=>$this->order_status[self::ORDER_CLOSE]['name'],
                'cancel_time'=>time()
            ];

            if ($info['coupon_id']){
                $coupon_model = new UserCoupon();
                $coupon_model->resetUserCoupon($info['coupon_id']);
            }

            if ($info['use_score']<0){
                User::score($info['use_score'],$info['user_id'],$info['order_no'].'订单关闭退回');
            }


            if ($info['parent_order_id']){
                $order_model = new OrderModel();

                $third_res = $order_model->order_cancel($info['hotel_id'],$order_id);
                if ($third_res['code']==0){
                    Db::rollback();
                    throw new \Exception('取消失败');
                }
                $data['third_order_status'] = 'delete';
            }

            $res = HotelThirdOrder::where(['order_id'=>$order_id])->update($data);
            Db::commit();
            return $res;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

    }

    //回调
    public function notify($out_trade_no,$paytype='wechat',$trxid)
    {
        $order = HotelThirdOrder::get(['order_no' => $out_trade_no]);
        if ($order->pay_status==0){
            if ($paytype=='balance'){
                User::money(-$order->pay_money,$order->user_id,'余额支付,订单编号:'. $order->order_no);
            }
            $order->pay_type = $paytype;
            $order->pay_status = 1;
            $order->pay_time = time();
            $order->setAttr('order_status',1);
            $order->order_status_name = $this->order_status[self::ORDER_WAIT_CHECKIN]['name'];
            $order->trxid = $trxid;
            $order->save();
            //使用积分扣除
            if ($order->use_score){
                User::score(-$order->use_score,$order->user_id,'订单积分抵扣,订单编号:'. $order->order_no);
            }
            //奖励积分
            if ($order->award_score){
                User::score($order->award_score,$order->user_id,'消费奖励积分,订单编号:'. $order->order_no);
            }
            if ($order->room_type_code){
                $hotel = new OrderModel();
                $res = $hotel->order_commit($order->order_id);
            }
        }
        return true;
    }

    //订单售后
    public function orderRefund($order_id)
    {
        $info = HotelThirdOrder::where(['order_id'=>$order_id])->find();

        if ($info['order_status']==4)return true;

        $data = [
            'order_status'=>self::ORDER_REFUND,
            'order_status_name'=>'退款中',
            'salestate'=>1,
            'refund_time'=>time()
        ];

        $res = HotelThirdOrder::where(['order_id'=>$order_id])->update($data);

        return $res;
    }

    //订单取消售后
    public function orderCancelRefund($order_id)
    {
        $info = HotelThirdOrder::where(['order_id'=>$order_id])->find();

        if ($info['order_status']==4)return true;

        $data = [
            'order_status'=>self::ORDER_WAIT_CHECKIN,
            'order_status_name'=>$this->order_status[self::ORDER_WAIT_CHECKIN]['name'],
            'salestate'=>2
        ];

        $res = HotelThirdOrder::where(['order_id'=>$order_id])->update($data);

        return $res;
    }
}
